package com.alibaba.citrus.cr.order.open.api.facade.service.handler;

import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crunifiedinventory.dto.request.AllocateOrderSyncRequest;
import com.epoch.app.crunifiedinventory.dto.response.AllocateOrderSyncResponse;
import com.epoch.app.crunifiedinventory.model.dto.AllocateOrderScItemDetailDTO;
import com.epoch.app.crunifiedinventory.model.enums.AllocateOrderStatus;
import com.epoch.app.crunifiedinventory.sdo.enums.AllocateOrderTypeEnum;
import com.epoch.app.mninventorycenter.model.dto.*;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 计划调拨
 *
 * @author mingyang
 * @since 2024/01/05
 */
@Component
public class PlanAllocateHandler extends AbstractAllocateOrderCreateHandler {

    private Log log = Log.getLogger(PlanAllocateHandler.class);

    @Override
    public Boolean support(TransferOrderCreateRequest request) {
        return Objects.equals(AllocateOrderTypeEnum.PLAN.getType(), request.getTransferOrderType());
    }

    @Override
    public TransferOrderCreateResponse handle(TransferOrderCreateRequest transferOrderCreateRequest, Map<String, ScItemResponse> scItemInfoMap, WarehouseQueryResponse receiveLogicWareId, WarehouseQueryResponse deliveryLogicWareId) {
        AllocateOrderSyncRequest allocateOrderSyncRequest = getAllocateOrderSyncRequest(transferOrderCreateRequest,scItemInfoMap, receiveLogicWareId, deliveryLogicWareId);
        allocateOrderSyncRequest.setFeatures(getFeaturesNew(receiveLogicWareId, deliveryLogicWareId, transferOrderCreateRequest));
        log.info("createAllocateApplyOrder.passiveSyncApi,PLAN,response:{}", JSON.toJSON(allocateOrderSyncRequest));
        Result<AllocateOrderSyncResponse> allocateOrderSyncResult = allocateOrderWriteService.passiveSyncApi(allocateOrderSyncRequest);
        log.info("createAllocateApplyOrder.passiveSyncApi,response:{}", JSON.toJSON(allocateOrderSyncResult));
        if(!allocateOrderSyncResult.isSuccess()){
            throw new FacadeException(allocateOrderSyncResult.getErrorCode(), allocateOrderSyncResult.getMessage());
        }
        AllocateOrderSyncResponse result = allocateOrderSyncResult.getResult();
        return getAllocateOrderCreateResponse(result.getCode(), result.getThirdAllocateOrderId(), result.getAllocateOrderDetailList());
    }

    /**
     * 计划调拨，创建调拨单入参
     * @param transferOrderCreate req
     * @param receiveLogicWareId 收货仓ID
     * @param deliveryLogicWareId 发货仓ID
     * @return req
     */
    private AllocateOrderSyncRequest getAllocateOrderSyncRequest(TransferOrderCreateRequest transferOrderCreate,
                                                                 Map<String, ScItemResponse> scItemInfoMap,
                                                                 WarehouseQueryResponse receiveLogicWareId,WarehouseQueryResponse deliveryLogicWareId){
        AllocateOrderSyncRequest allocateOrderSync = new AllocateOrderSyncRequest();
        allocateOrderSync.setBusinessType(transferOrderCreate.getBusinessType());
        allocateOrderSync.setFromSys(transferOrderCreate.getFromSys());
        allocateOrderSync.setSubmitFlag(Boolean.parseBoolean(transferOrderCreate.getSubmitFlag()));
        allocateOrderSync.setReturnOrder(Boolean.parseBoolean(transferOrderCreate.getReturnFlag()));
        allocateOrderSync.setType(transferOrderCreate.getTransferOrderType());

        allocateOrderSync.setReceiveWarehouseId(receiveLogicWareId.getParentId());
        allocateOrderSync.setReceiveAreaId(receiveLogicWareId.getId());
        allocateOrderSync.setShipWarehouseId(deliveryLogicWareId.getParentId());
        allocateOrderSync.setShipAreaId(deliveryLogicWareId.getId());

        allocateOrderSync.setDocDate(strToDate(transferOrderCreate.getOrderDate()));
        allocateOrderSync.setExpectedDeliveryDate(strToDate(transferOrderCreate.getExpectedDeliveryDate()));
        allocateOrderSync.setShipMethod(Integer.parseInt(transferOrderCreate.getShipMethodCode()));
        allocateOrderSync.setRemark(transferOrderCreate.getHeadRemark());
        allocateOrderSync.setRequestId(transferOrderCreate.getRequestId());
        allocateOrderSync.setThirdAllocateOrderId(transferOrderCreate.getThirdAllocateOrderId());

        allocateOrderSync.setAllocateApplyOrderCode(transferOrderCreate.getAllocateApplyOrderCode());
        allocateOrderSync.setAllocateApplyOrderId(transferOrderCreate.getAllocateApplyOrderId());
        allocateOrderSync.setApplyOrgId(transferOrderCreate.getApplyOrgId());
        allocateOrderSync.setRelatedAllocateOrderCode(transferOrderCreate.getRelatedAllocateOrderCode());
        allocateOrderSync.setFulfillmentTypeCode(transferOrderCreate.getFulfillmentTypeCode());

        allocateOrderSync.setPriority("100".equals(transferOrderCreate.getPriority()) ? 100 : 1);

        // 0-是，1-否 不传的情况下默认“是”
        allocateOrderSync.setAutoFulfillment(transferOrderCreate.getAutoFulfillment());
        allocateOrderSync.setOrderTag(transferOrderCreate.getOrderTag());
        allocateOrderSync.setCreator(transferOrderCreate.getCreator());
        allocateOrderSync.setTakeEffectDate(transferOrderCreate.getTakeEffectDate());
        allocateOrderSync.setProductGroup(transferOrderCreate.getProductGroupCode());
        allocateOrderSync.setTransferWarehouseId(transferOrderCreate.getTransferWarehouseId());

        List<TransferOrderDetailRequest> transferOrderDetailList = transferOrderCreate.getTransferOrderDetailList();
        List<AllocateOrderScItemDetailDTO> collect = transferOrderDetailList.stream().map(x -> {
            ScItemResponse scItemResponse = scItemInfoMap.get(x.getGoodsCode());
            AllocateOrderScItemDetailDTO allocateOrderScItemDetail = new AllocateOrderScItemDetailDTO();
            allocateOrderScItemDetail.setScItemId(scItemResponse.getScItemId());
            allocateOrderScItemDetail.setScItemCode(x.getGoodsCode());
            allocateOrderScItemDetail.setTitle(scItemResponse.getTitle());
            allocateOrderScItemDetail.setQuantity(x.getQuantity());
            allocateOrderScItemDetail.setUnit(x.getUnit());
            allocateOrderScItemDetail.setProductDate(x.getProductDate());
            allocateOrderScItemDetail.setRemark(x.getLineRemark());
            allocateOrderScItemDetail.setOutAllocateOrderLineNo(x.getOutDetailLineNo());
            allocateOrderScItemDetail.setOutAllocateOrderLineId(x.getOutDetailLineNo());
            allocateOrderScItemDetail.setThirdLineNo(x.getOutDetailLineNo());
            allocateOrderScItemDetail.setRelatedAllocateSubOrderId(x.getRelatedAllocateSubOrderNo());
            allocateOrderScItemDetail.setAllocateApplyOrderLineId(x.getAllocateApplyOrderLineId());
            return allocateOrderScItemDetail;
        }).collect(Collectors.toList());
        allocateOrderSync.setAllocateOrderScItemDetails(collect);
        return allocateOrderSync;
    }
}
